package com.kg.fiber.common;

import java.util.Queue;

import com.google.common.collect.Lists;

import lombok.Getter;

public abstract class Pool<T> {

	@Getter
	private int total = 0;
	
	private Queue<T> queue = Lists.newLinkedList();
	
	
	public Pool(){
	}
	
	public int getUsed() {
		return total - queue.size();
	}

	public synchronized T get() {
		
		T data = queue.poll();
		if(data == null) {
			data = create();
			if(data != null) {
				total++;
			}
		}
		
		beforeGet(data);
		
		return data;
	}
	
	protected abstract T create();
	
	public synchronized void back(T data) {
		if(data != null) {
			//System.out.println("Pci1714Data release");
			afterBack(data);
			queue.offer(data);
		}
	}
	
	protected void beforeGet(T t) {
		
	}
	
	protected void afterBack(T t) {
		
	}
	
}
